﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Xml.Linq;

namespace msBsc.AppLogic.Cfg
{
    public class SystemSet
    {
        public static bool IsWebSys = true;

        private static SystemSet _oSystemSet = new SystemSet();
        public static SystemSet oSystemSet
        {
            get
            {
                if (_oSystemSet == null)
                {
                    lock (_oSystemSet)
                    {
                        _oSystemSet = new SystemSet();
                    }
                }
                return _oSystemSet;
            }
        }

        //系统参数初始化入口
        public void InitSys(bool _IsWebSys)
        {
            try
            {
                IsWebSys = _IsWebSys;
                //oSystemSet.InitSoftInfo(_ottSystemType);
                //SystemFileDir.FileDir.initFileDir();
                //log4net.Config.XmlConfigurator.Configure();
            }
            catch (Exception err)
            {
                ApplicationLog.WriteFile(err);
            }
        }

        public SystemSet()
        {
            ConfigHttpUrlBase = GetAppSettings("HttpPath");
            if (!ConfigHttpUrlBase.EndsWith("/"))
            {
                ConfigHttpUrlBase = ConfigHttpUrlBase + "/";
            }
            dirDumm = GetAppSettings("dirDumm");

            initdicDataSysSet();
            ////InitSoftInfo(_ottSystemType);
            //InitSetDic();
            //strAdminUserCde = Epm.AppLogic.Framework.EditConfig.GetAppSettings("SYS_ADMIN_CDE");
            //strAdminUserPass = Epm.AppLogic.Framework.EditConfig.GetAppSettings("SYS_ADMIN_PASS");
            //if (strAdminUserCde == null || strAdminUserCde == string.Empty)
            //{
            //    strAdminUserCde = "SYSADMIN";
            //}
            //if (strAdminUserPass == null || strAdminUserPass == string.Empty)
            //{
            //    strAdminUserPass = "000000";
            //}

        }
        ~SystemSet()
        {
            //try
            //{
            //    SaveSysSet(false);
            //}
            //catch
            //{
            //}
        }
        /// <summary>
        /// 从内存获取当前配置
        /// </summary>
        /// <param name="strSettingsNme"></param>
        /// <returns></returns>
        public string GetAppSettings(string strSettingsNme)
        {
            string strSettingsValue = System.Configuration.ConfigurationManager.AppSettings[strSettingsNme];
            if (strSettingsValue == null) return "";
            if (strSettingsValue.StartsWith("Cry:") && strSettingsValue.Length > 4)
            {
                return DesCry.uncMe(strSettingsValue.Substring(4, strSettingsValue.Length - 4), "configCry");
            }
            else
            {
                return strSettingsValue;
            }
        }
        public T GetAppSettings<T>(string _strkey)
        {
            T result = default(T);
            string strVal = GetAppSettings(_strkey);
            if (typeof(T) == typeof(int))
            {
                int n = 0;
                if (int.TryParse(strVal, out n))
                {
                    result = (T)(object)n;
                }
            }
            else if (typeof(T) == typeof(decimal))
            {
                decimal n = 0M;
                if (decimal.TryParse(strVal, out n))
                {
                    result = (T)(object)n;
                }
            }
            else if (typeof(T) == typeof(DateTime))
            {
                DateTime n = DateTime.MinValue;
                if (DateTime.TryParse(strVal, out n))
                {
                    result = (T)(object)n;
                }
            }
            else
            {
                result = (T)(object)strVal;
            }
            return result;
        }
        public string ApplicationName
        {
            get
            {
                if (!string.IsNullOrEmpty(GetAppSettings("AppName")))
                    return GetAppSettings("AppName");
                else
                    return "地接客网站";
            }
        }

        #region Log Properties
        //public  string LogFolder
        //{
        //    get
        //    {
        //        if (!string.IsNullOrEmpty(GetAppSettings("LogFolder")))
        //            return GetAppSettings("LogFolder");
        //        else
        //            return "地接客网站"; 

        //    }
        //}
        public string LogFileDatetimeFormat
        {
            get
            {
                return GetAppSettings("LogFileDatetimeFormat");
            }
        }
        #endregion Log Properties


        private SynDictionary _dicDataSysSet = new SynDictionary(true);
        /// <summary>
        /// CONSTANT_DISP_TEXT,CONSTANT_VALUE_DESC
        /// </summary>
        public SynDictionary dicDataSysSet
        {
            get
            {
                return _dicDataSysSet;
            }
        }

        public string getSysSetVal(string _strkey)
        {
            if (_dicDataSysSet.ContainsKey(_strkey))
            {
                return _dicDataSysSet[_strkey].ToString();
            }
            return "";
        }

        public T getSysSetVal<T>(string _strkey)
        {
            T result = default(T);
            if (_dicDataSysSet.ContainsKey(_strkey))
            {
                string stmt = _dicDataSysSet[_strkey].ToString();
                if (typeof(T) == typeof(int))
                {
                    int n = 0;
                    if (int.TryParse(stmt, out n))
                    {
                        result = (T)(object)int.Parse(stmt);
                    }
                }
                else if (typeof(T) == typeof(decimal))
                {
                    decimal n = 0M;
                    if (decimal.TryParse(stmt, out n))
                    {
                        result = (T)(object)decimal.Parse(stmt);
                    }
                }
                else if (typeof(T) == typeof(DateTime))
                {
                    DateTime n = DateTime.MinValue;
                    if (DateTime.TryParse(stmt, out n))
                    {
                        result = (T)(object)DateTime.Parse(stmt);
                    }
                }
                else
                {
                    result = (T)(object)stmt;
                }
            }
            return result;
        }

        public void initdicDataSysSet()
        {
            using (Epm.AppLogic.Framework.CDbAccess objtem1 = new Epm.AppLogic.Framework.CDbAccess())
            {
                DataSet _ds = objtem1.QueryBySQL("SELECT CONSTANT_CDE,CONSTANT_VALUE  FROM BSE_CONSTANT_DICT ORDER BY SEQ_NUM ASC");
                _dicDataSysSet.Clear();
                for (int i = _ds.Tables[0].Rows.Count - 1; i >= 0; i--)
                {
                    _dicDataSysSet.Add(_ds.Tables[0].Rows[i]["CONSTANT_CDE"].ToString(), _ds.Tables[0].Rows[i]["CONSTANT_VALUE"].ToString());
                }
                //DataSet _ds = objtem1.QueryBySQL("SELECT SYS_SET_CDE,SYS_SET_VALUE  FROM SYS_SET_DICT ORDER BY SEQ_NUM ASC");
                //_dicDataSysSet.Clear();
                //for (int i = _ds.Tables[0].Rows.Count - 1; i >= 0; i--)
                //{
                //    _dicDataSysSet.Add(_ds.Tables[0].Rows[i]["SYS_SET_CDE"].ToString(), _ds.Tables[0].Rows[i]["SYS_SET_VALUE"].ToString());
                //}
            }
        }


        public string strAdminUserCde
        {
            get
            {
                string _tm1 = getSysSetVal("_SYS_ADMIN_CDE");
                if (_tm1 == string.Empty)
                {
                    _tm1 = "admin";
                }
                return _tm1;
            }
        }
        public string strAdminUserPass
        {
            get
            {
                string _tm1 = getSysSetVal("_SYS_ADMIN_PASS");
                if (_tm1 == string.Empty)
                {
                    _tm1 = "admin";
                }
                return _tm1;
            }
        }
        //public string strAdminUserPass = "";
        //private msBcc.AppLogic.Cfg.SynDictionary _pSetItems = new msBcc.AppLogic.Cfg.SynDictionary(true);
        //private  string strSetFPath = ".\\SystemSet.Set";
        //private  bool _blUseWebConfig = true;
        //private  DataSet ds = GetDs();
        //public  bool blUseWebConfig
        //{
        //    get
        //    {
        //        return _blUseWebConfig;
        //    }
        //    set
        //    {
        //        if (_blUseWebConfig != value)
        //        {
        //            _blUseWebConfig = value;
        //            lock (ds)
        //            {
        //                ds = GetDs();
        //            }
        //        }
        //    }
        //}
        //public  void UpdateDs()
        //{
        //    lock (ds)
        //    {
        //        if (!_blUseWebConfig && System.IO.File.Exists(strSetFPath))
        //        {
        //            ds.ReadXml(strSetFPath);
        //        } 
        //        else
        //        {
        //            ds = oEditConfig.GetConfigAppSData();
        //            ds.Tables[0].PrimaryKey = new DataColumn[] { ds.Tables[0].Columns["F_NAME"] };
        //        }
        //    }
        //}
        //private void InitSetDic()
        //{
        //    _pSetItems.Clear();
        //    Epm.AppLogic.Framework.EditConfig oEditConfig = new Epm.AppLogic.Framework.EditConfig();
        //    DataSet _ds = oEditConfig.GetConfigAppSData();
        //    for (int i = 0; i < _ds.Tables[0].Rows.Count; i++)
        //    {
        //        _pSetItems.Add(_ds.Tables[0].Rows[i]["F_NAME"].ToString(), _ds.Tables[0].Rows[i]["F_VALUE"].ToString());
        //    }



        //    //DataSet _ds = new DataSet();
        //    //if (!_blUseWebConfig && System.IO.File.Exists(strSetFPath))
        //    //{
        //    //    _ds.ReadXml(strSetFPath);
        //    //}
        //    //else if (!_blUseWebConfig)
        //    //{
        //    //    DataTable dt = new DataTable();
        //    //    dt.Columns.Add("F_NAME", typeof(string));
        //    //    dt.Columns.Add("F_VALUE", typeof(string));
        //    //    dt.PrimaryKey = new DataColumn[] { dt.Columns["F_NAME"] };
        //    //    _ds.Tables.Add(dt);
        //    //    _ds.AcceptChanges();
        //    //    _ds.WriteXml(strSetFPath, XmlWriteMode.WriteSchema);
        //    //}
        //    //else
        //    //{
        //    //    _ds = oEditConfig.GetConfigAppSData();
        //    //    _ds.Tables[0].PrimaryKey = new DataColumn[] { _ds.Tables[0].Columns["F_NAME"] };
        //    //}
        //    //return _ds;
        //}

        //public DataSet GetSetDataSet()
        //{
        //    //lock (ds)
        //    //{
        //    Epm.AppLogic.Framework.EditConfig oEditConfig = new Epm.AppLogic.Framework.EditConfig();
        //    return oEditConfig.GetConfigAppSData(); ;
        //    //}
        //}

        //public void SetSetDataSet(DataSet _dstm)
        //{
        //    Epm.AppLogic.Framework.EditConfig oEditConfig = new Epm.AppLogic.Framework.EditConfig();
        //    oEditConfig.SaveConfigAppSData(_dstm);
        //    InitSetDic();
        //}

        //public void SaveSysSet(bool blNeedDel=true)
        //{
        //    try
        //    {
        //        Epm.AppLogic.Framework.EditConfig oEditConfig = new Epm.AppLogic.Framework.EditConfig();
        //        string[] arrstrtem111 = _pSetItems.Keys;
        //        DataSet _ds = oEditConfig.GetConfigAppSData();
        //        _ds.AcceptChanges();
        //        for (int i = 0; i < arrstrtem111.Length; i++)
        //        {
        //            DataRow[] arrrowtem12 = _ds.Tables[0].Select("F_NAME='" + arrstrtem111[i] + "'");
        //            if (arrrowtem12.Length > 0 && arrrowtem12[0]["F_VALUE"].ToString().Trim().ToUpper() != _pSetItems[arrstrtem111[i]].ToString().Trim().ToUpper())
        //            {
        //                arrrowtem12[0]["F_VALUE"] = _pSetItems[arrstrtem111[i]].ToString();
        //            }
        //            else if (arrrowtem12.Length <= 0 )
        //            {
        //                DataRow drNew = _ds.Tables[0].NewRow();
        //                drNew["F_NAME"] = arrstrtem111[i];
        //                drNew["F_VALUE"] = _pSetItems[arrstrtem111[i]];
        //                _ds.Tables[0].Rows.Add(drNew);
        //            }
        //        }

        //        if (blNeedDel)
        //        {
        //            DataRow[] arrrowtem13 = _ds.Tables[0].Select("F_NAME NOT IN('" + string.Join("','", arrstrtem111) + "')");
        //            for (int i = arrrowtem13.Length - 1; i >= 0; i--)
        //            {
        //                arrrowtem13[i].Delete();
        //            }
        //        }
        //        if (_ds.HasChanges())
        //        {
        //            oEditConfig.SaveConfigAppSData(_ds);
        //        }
        //    }
        //    catch (Exception err)
        //    {
        //        ApplicationLog.AddSysLog(err);
        //    }
        //}


        //public string GetSetValue(string strSetNme)
        //{
        //    if (_pSetItems[strSetNme] == null)
        //    {
        //        return "";
        //    }
        //    else
        //    {
        //        return _pSetItems[strSetNme].ToString();
        //    }
        //}

        //public  void SetSetValue(string strSetNme, string strValue)
        //{
        //    _pSetItems[strSetNme] = strValue;
        //    //lock (ds)
        //    //{
        //    //    DataRow arrrowtem1 = ds.Tables[0].Rows.Find(new string[] { strSetNme });
        //    //    //DataRow[] arrR = ds.Tables[0].Select("F_NAME='" + strSetNme + "'");
        //    //    if (arrrowtem1 != null)
        //    //        arrrowtem1["F_VALUE"] = strValue;
        //    //    else
        //    //    {
        //    //        DataRow drNew = ds.Tables[0].NewRow();
        //    //        drNew["F_NAME"] = strSetNme;
        //    //        drNew["F_VALUE"] = strValue;
        //    //        ds.Tables[0].Rows.Add(drNew);
        //    //    }

        //    //    if (ds.HasChanges())
        //    //    {
        //    //        ds.AcceptChanges();
        //    //    }
        //    //    if (!_blUseWebConfig)
        //    //    {
        //    //        ds.WriteXml(strSetFPath, XmlWriteMode.WriteSchema);
        //    //    }
        //    //    else
        //    //    {
        //    //        oEditConfig.SaveConfigAppSData(ds);
        //    //    }
        //    //}
        //}
        /// <summary>
        /// ,以/结尾
        /// </summary>
        public string ConfigHttpUrlBase = "";
        public string DefaultCountry = "";
        public string DefaultCity = "";
        public string DefaultDestination = "";
        public string dirDumm = "";

        //private bool InitSoftInfo(Epm.AppLogic.Framework.ApplicationInfo.ttSystemType _ottSystemType)
        //{
        //if (HttpContext.Current == null)
        //{
        //    Epm.AppLogic.Framework.ApplicationInfo.SystemType = Epm.AppLogic.Framework.ApplicationInfo.ttSystemType.WinForm;
        //}
        //else
        //{
        //    Epm.AppLogic.Framework.ApplicationInfo.SystemType = Epm.AppLogic.Framework.ApplicationInfo.ttSystemType.WebForm;
        //}



        //SysInfo oSysInfo = new SysInfo();
        //Epm.AppLogic.Framework.FrameworkSysInfo.SoftVersionBit = oSysInfo.SoftVersionBit;
        //Epm.AppLogic.Framework.FrameworkSysInfo.SoftVersions = oSysInfo.SoftVersions;
        //Epm.AppLogic.Framework.FrameworkSysInfo.strPrjCode = oSysInfo.strPrjCode;
        //Epm.AppLogic.Framework.FrameworkSysInfo.strPrjNme = oSysInfo.strPrjNme;

        //Epm.AppLogic.Framework.ApplicationInfo.initSys(_ottSystemType);
        //    return true;
        //}



        //private string GetValueDesc(string strValue)
        //{
        //    System.Data.DataRow[] arrRow = Epm.AppLogic.Framework.ApplicationInfo.DataConst.Tables[0].Select("CONSTANT_CATEGORY_CID='SYS_SETTING' AND CONSTANT_VALUE='" + strValue + "'");
        //    if (arrRow.Length > 0)
        //        return arrRow[0]["CONSTANT_VALUE_DESC"].ToString();
        //    else
        //        return "";
        //}


        public int AutoNotifyInterval
        {
            get
            {
                return getSysSetVal<int>("_AUTO_NOTIFY_INTERVAL");
                //string strTem = GetValueDesc("AUTO_NOTIFY_INTERVAL");
                //int iTem = 60;
                //if (int.TryParse(strTem, out iTem))
                //    return iTem;
                //else
                //    return 60;
            }
        }
        ///// <summary>
        ///// SMTP服务器验证方式,Login,Plain,CRAMMD5
        ///// </summary>
        //public string AutoNotifyMailSendAuth
        //{
        //    get
        //    {
        //        return getSysSetVal("_AUTO_NOTIFY_MAIL_SEND_AUTH");
        //    }
        //}
        /// <summary>
        /// smtp.163.com
        /// </summary>
        public string AutoNotifyMailSendName
        {
            get
            {
                return getSysSetVal("_AUTO_NOTIFY_MAIL_SEND_NAME");
            }
        }

        /// <summary>
        /// smtp.163.com
        /// </summary>
        public string AutoNotifyMailServer
        {
            get
            {
                return getSysSetVal("_AUTO_NOTIFY_MAIL_SERVER");
            }
        }

        public string AutoNotifyMailServerPort
        {
            get
            {
                string _strPort = getSysSetVal("_AUTO_NOTIFY_MAIL_SEND_PORT");
                if (_strPort == string.Empty)
                    _strPort = "25";
                return _strPort;
            }
        }

        /// <summary>
        /// aaa@163.com
        /// </summary>
        public string AutoNotifyMailAddress
        {
            get
            {
                return getSysSetVal("_AUTO_NOTIFY_MAIL_ADDRESS");
            }
        }

        /// <summary>
        /// *****
        /// </summary>
        public string AutoNotifyMailPass
        {
            get
            {
                return getSysSetVal("_AUTO_NOTIFY_MAIL_PASS").ToLower();
            }
        }


        /// <summary>
        /// 4163645
        /// </summary>
        public string AutoNotifyQQ
        {
            get
            {
                return getSysSetVal("_AUTO_NOTIFY_QQ");
            }
        }

        /// <summary>
        /// ****
        /// </summary>
        public string AutoNotifyQQPass
        {
            get
            {
                return getSysSetVal("_AUTO_NOTIFY_QQ_PASS").ToLower();
            }
        }

        /// <summary>
        /// ****
        /// </summary>
        public string AutoNotifyMsnPass
        {
            get
            {
                return getSysSetVal("_AUTO_NOTIFY_MSN_PASS").ToLower();
            }
        }

        /// <summary>
        /// ANFR@163.COM
        /// </summary>
        public string AutoNotifyMsn
        {
            get
            {
                return getSysSetVal("_AUTO_NOTIFY_MSN");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string ServerVersion
        {
            get
            {
                return getSysSetVal("_SOFT_SERVER_VERSION");
            }
        }




    }
}
